package algorithm_demo.demo02;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

/**
 * 二叉树的宽度优先遍历,用队列
 *
 * @author Api
 * @date 2023/2/7 23:48
 */
public class Code02_WidthFirstTraversalOfBinaryTree {
    public static class TreeNode {
        public int value;
        public TreeNode left;
        public TreeNode right;
    }

    //二叉树按层遍历，从左往右遍历
    public static void level(TreeNode head) {
        if (head == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(head);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.println(cur.value);
            if (cur.left != null) {
                queue.add(cur.left);
            }
            if (cur.right != null) {
                queue.add(cur.right);
            }
        }
    }

    //二叉树的最大宽度，使用Map的方式
    public static int maxWidthUseMap(TreeNode head) {
        if (head == null) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(head);
        //key在哪一层，value
        Map<TreeNode, Integer> levelMap = new HashMap<>();
        levelMap.put(head, 1);//头节点
        int curLevel = 1;//当前正在统计哪一层的宽度
        int curLevelNodes = 0;//当前层curLevel层，宽度目前是多少
        int max = 0;
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            int curNodeLevel = levelMap.get(cur);
            if (cur.left != null) {
                levelMap.put(cur.left, curNodeLevel + 1);
                queue.add(cur.left);
            }
            if (cur.right != null) {
                levelMap.put(cur.right, curNodeLevel + 1);
                queue.add(cur.right);
            }
            if (curNodeLevel == curLevel) {
                curLevelNodes++;
            } else {
                max = Math.max(max, curLevelNodes);
                curLevel++;
                curLevelNodes = 1;
            }
        }
        max = Math.max(max, curLevelNodes);
        return max;
    }


}
